package base.网络编程.TCP.服务器上传;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss = new ServerSocket(10000);

        while (true){
            Socket socket = ss.accept();
//            new Thread(new Myrunnable(socket)).start();
            /*线程池优化*/
            ExecutorService pool = Executors.newCachedThreadPool();
            pool.submit(new Myrunnable(socket));
        }


    }
}
class Myrunnable implements Runnable{
    Socket socket = null;
    Myrunnable (Socket socket){
        this.socket = socket;
    }
    @Override
    public void run() {
        try {
            String fileName = UUID.randomUUID().toString().replace("-", "");
            File file = new File("src\\base\\网络编程\\TCP\\服务器上传\\"+fileName+".png");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
            byte[] bytes = new byte[1024];
            int len;
            while ((len = bis.read(bytes)) != -1){
                bos.write(bytes,0,len);
            }
            bos.flush();

            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            bw.write("上传成功");
            bw.flush();

        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

    }
}
